/**
 * 图片压缩工具
 */

/**
 * 压缩图片
 * @param {File} file - 要压缩的图片文件
 * @param {Object} options - 压缩选项
 * @param {Number} options.maxWidth - 最大宽度
 * @param {Number} options.maxHeight - 最大高度
 * @param {Number} options.quality - 压缩质量(0-1)
 * @returns {Promise<Blob>} - 返回压缩后的图片Blob对象
 */
export const compressImage = (file, options = {}) => {
  const { maxWidth = 1920, maxHeight = 1080, quality = 0.8 } = options;

  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (e) => {
      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        let width = img.width;
        let height = img.height;

        // 计算缩放比例
        if (width > maxWidth) {
          height = Math.round((height * maxWidth) / width);
          width = maxWidth;
        }
        if (height > maxHeight) {
          width = Math.round((width * maxHeight) / height);
          height = maxHeight;
        }

        const canvas = document.createElement("canvas");
        const ctx = canvas.getContext("2d");
        canvas.width = width;
        canvas.height = height;

        // 绘制图片
        ctx.drawImage(img, 0, 0, width, height);

        // 转换为Blob
        canvas.toBlob(
          (blob) => {
            resolve(blob);
          },
          file.type,
          quality,
        );
      };
      img.onerror = reject;
    };
    reader.onerror = reject;
  });
};

/**
 * 检查文件是否为图片
 * @param {File} file - 要检查的文件
 * @returns {Boolean} - 是否为图片
 */
export const isImage = (file) => {
  return file.type.startsWith("image/");
};

/**
 * 检查文件是否为视频
 * @param {File} file - 要检查的文件
 * @returns {Boolean} - 是否为视频
 */
export const isVideo = (file) => {
  return file.type.startsWith("video/");
};

/**
 * 获取文件大小描述
 * @param {Number} size - 文件大小（字节）
 * @returns {String} - 文件大小描述
 */
export const getFileSizeDescription = (size) => {
  if (size < 1024) {
    return size + "B";
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + "KB";
  } else if (size < 1024 * 1024 * 1024) {
    return (size / (1024 * 1024)).toFixed(2) + "MB";
  } else {
    return (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }
};
